﻿using System;
using System.ComponentModel;
using Loki;
using Loki.Commands;
using Luna.Model.Project;

namespace Luna.UI.Project
{
    public class ProjectListViewModel : LunaViewModel
    {
        public LokiCollection<DisplayableProject> Projects { get; private set; }

        #region  SelectedProjectIndex
        private static PropertyChangedEventArgs _SelectedProjectIndexChangeArgs = ObservableHelper.CreateArgs<ProjectListViewModel>(x => x.SelectedProjectIndex);

        private int? _SelectedProjectIndex;

        public int? SelectedProjectIndex
        {
            get
            {
                return _SelectedProjectIndex;
            }

            set
            {
                if (value != _SelectedProjectIndex)
                {
                    _SelectedProjectIndex = value;
                    NotifyChanged(_SelectedProjectIndexChangeArgs);
                }
            }
        }
        #endregion

        public ProjectListViewModel()
        {
            Projects = CreateCollection<DisplayableProject>();

            Open = Commands.Create();
            Add = Commands.Create();

            Init += ProjectListViewModel_Init;
            Load += ProjectListViewModel_Load;
        }

        private void ProjectListViewModel_Load(object P_Sender, EventArgs e)
        {
            Projects.Synchronize<IProject>(
                   ApplicationModel.Project.Projects,
                   ConvertProject,
                   (i, d) => i.ID == d.ID,
                   d => d.Name);
        }

        private void ConvertProject(IProject P_Source, DisplayableProject P_Dest)
        {
            P_Dest.ID = P_Source.ID;
            P_Dest.AllocatedAmount = P_Source.Budget;
            P_Dest.Description = P_Source.Description;
            P_Dest.Name = P_Source.Name;
        }

        private void ProjectListViewModel_Init(object P_Sender, EventArgs e)
        {
            Commands.Handle(Add, Add_Execute);
            Commands.Handle(Open, Open_CanExecute, Open_Execute);
        }

        public ICommand Open { get; private set; }

        public ICommand Add { get; private set; }

        private void Add_Execute(object P_Sender, CommandEventArgs e)
        {
            LunaCommands.Application.LOAD.Execute(ApplicationModel.Project.Create<IEditableProject>());
        }

        public void Open_CanExecute(object P_Sender, CanExecuteCommandEventArgs e)
        {
            e.CanExecute |= SelectedProjectIndex.HasValue;
        }

        public void Open_Execute(object P_Sender, CommandEventArgs e)
        {
            Guid L_SelectedAccountID = Projects[SelectedProjectIndex.Value].ID;
            IProject L_Project = ApplicationModel.Project.Projects[L_SelectedAccountID];
            if (L_Project != null)
            {
                LunaCommands.Application.LOAD.Execute(L_Project);
            }
        }
    }
}
